package com.tf_cut.admin.seller.controller;

import com.alibaba.fastjson.JSON;
import com.tf_cut.admin.agent.vo.AgentAccountVo;
import com.tf_cut.admin.annotation.Decrypt;
import com.tf_cut.admin.annotation.Encrypt;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.common.pojo.PageInfo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.platform.vo.RechargeVo;
import com.tf_cut.admin.seller.vo.SellerAccountDetailVo;
import com.tf_cut.admin.seller.vo.SellerAndAccountVo;
import com.tf_cut.admin.seller.vo.SellerExcelVo;
import com.tf_cut.admin.seller.vo.SellerProjectVo;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.sysuser.service.SysUserService;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.util.ExcelUtil;
import com.tf_cut.admin.util.MD5Util;
import com.tf_cut.admin.util.SecurityUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/seller/")
@Slf4j
public class SellerController {
	
	@Autowired
	private BackEndApi sellerApi;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysAuthorityService sysAuthorityService;
	@Autowired
	private SysUserAuthorityService sysUserAuthorityService;
	@Autowired
	private ResourceLoader resourceLoader;

	@Value("${mobile.upload.path}")
	private String filePath;

	private String uploadPath="mobile/upload/";

	@GetMapping("queryProject")
	public ModelAndView sellerProject() {
		return new ModelAndView("seller/queryProject", "queryProject", null);
	}

	// 进入商户清单页面
	@GetMapping("sellerlist")
    public ModelAndView sellerList() {
        return new ModelAndView("seller/sellerlist", "seller", null);
    }
	
	// 进入新增商户页面
	@GetMapping("sellerinsert")
    public ModelAndView sellerInsert() {
        return new ModelAndView("seller/sellerinsert", "seller", null);
    }
	
	// 进入新增商户页面
	@GetMapping("sellerimport")
    public ModelAndView sellerImport() {
        return new ModelAndView("seller/sellerimport", "seller", null);
    }

    @GetMapping("balance")
	public ModelAndView balance(){
		return new ModelAndView("seller/balance","seller",null);
	}
    
    @GetMapping("query/dtls")
	public ModelAndView queryDtls(){
		return new ModelAndView("seller/queryProjectDtls","seller",null);
	}

	@GetMapping("balance/dtls")
	public ModelAndView balanceDtls(){
		return new ModelAndView("seller/balanceDtls","seller",null);
	}
	
	
	// 进入商户加款页面
	@GetMapping("addmoney/{id}")
    public ModelAndView addMoney(@PathVariable("id")String sellerId) {
		SellerAccountDetailVo avo = SellerAccountDetailVo.builder()
				.sellerId(sellerId)
				.operType(1)
				.build();
        return new ModelAndView("seller/addmoney", "seller", avo);
    }
	
	// 进入商户扣款页面
	@GetMapping("delMoney/{id}")
    public ModelAndView delMoney(@PathVariable("id")String sellerId) {
		SellerAccountDetailVo avo = SellerAccountDetailVo.builder()
				.sellerId(sellerId)
				.operType(-1)
				.build();
        return new ModelAndView("seller/delmoney", "seller", avo);
    }
	
	// 进入修改商户页面
	@GetMapping("sellerinfo")
    public ModelAndView sellerInfo(String sellerId) {
		SellerAndAccountVo avo = null == sellerId ? 
				new SellerAndAccountVo() : 
					JSON.parseObject(sellerApi.getSeller(sellerId),SellerAndAccountVo.class);
        return new ModelAndView("seller/sellerinfo", "seller", avo);
    }
	
	// 进入网商银行信息查看页面
	@GetMapping("queryRegister")
    public ModelAndView queryRegister() {
//		SellerAndAccountVo avo = null == sellerId ? 
//				new SellerAndAccountVo() : 
//					JSON.parseObject(sellerApi.getSeller(sellerId),SellerAndAccountVo.class);
        return new ModelAndView("seller/queryRegister", "seller", null);
    }
	
	// 新增/修改商户
	@SuppressWarnings("unchecked")
	@PostMapping("saveSeller")
    public Result<SellerAndAccountVo> saveSeller(SellerAndAccountVo avo) {
		Result<SellerAndAccountVo> result = null;
		try {

			SellerAndAccountVo nameV = new SellerAndAccountVo();
			nameV.setSellerCompanyName(avo.getSellerCompanyName());
			String nameRes = sellerApi.qryByCondition(JSON.toJSONString(nameV));
			List<SellerAndAccountVo> nameList = JSON.parseArray(nameRes,SellerAndAccountVo.class);

			SellerAndAccountVo loginV = new SellerAndAccountVo();
			loginV.setLoginName(avo.getSellerMobile());
			String loginRes = sellerApi.qryByCondition(JSON.toJSONString(loginV));
			List<SellerAndAccountVo> loginList = JSON.parseArray(loginRes,SellerAndAccountVo.class);

			SysUserVo sysUserVo= sysUserService.initUser(avo.getSellerMobile(),avo.getSellerMobile(),"SELLER_USER").getData();

			String rtnJson = "";

			if(StringUtils.isEmpty(avo.getSellerId())) {
				if (!nameList.isEmpty()) {
					return Result.of(avo, false, "企业名称重复");
				}
				if(!loginList.isEmpty()){
					return Result.of(avo, false, "手机号码重复");
				}

				avo.setSellerState("Y"); // 默认不冻结
                avo.setLoginId(sysUserVo.getUserId());
                avo.setLoginName(sysUserVo.getLoginName());
				rtnJson = sellerApi.insertSellerAndAccount(JSON.toJSONString(avo));
				result = JSON.parseObject(rtnJson, Result.class);
			} else {
				Result<SellerAndAccountVo> result1 = Result.of(avo);
				nameList.forEach(vo -> {
					if(!vo.getSellerId().equalsIgnoreCase(avo.getSellerId())){
						result1.setFlag(false);
						result1.setMsg("企业名称重复");
					}
				});
				loginList.forEach(vo -> {
					if(!vo.getSellerId().equalsIgnoreCase(avo.getSellerId())){
						result1.setFlag(false);
						result1.setMsg("手机号码重复");
					}
				});
				if(!result1.isFlag()){
					return result1;
				}

				rtnJson = sellerApi.updateSellerInfo(JSON.toJSONString(avo));
				result = JSON.parseObject(rtnJson, Result.class);
			}
		}catch (Exception e){
			log.error("saveSeller error:{}",e.getMessage(),e);
			avo.setSellerId(null);
			result = Result.of(avo);
			result.setFlag(false);
		}
		return result;
    }

	private boolean saveSellerAuthority(Result<SysUserVo> save) {
		List<SysAuthorityVo> seller_user = this.sysAuthorityService.list(SysAuthorityVo.builder().authorityName("SELLER_USER").build()).getData();
		if(seller_user==null||seller_user.isEmpty()){
			return true;
		}
		SysUserAuthorityVo build = SysUserAuthorityVo.builder().userId(save.getData().getUserId())
				.authorityId(seller_user.get(0).getAuthorityId()).createTime(new Date()).build();

		this.sysUserAuthorityService.save(build);
		return false;
	}

	private boolean setSellerAuthority() {
		List<SysAuthorityVo> seller_user = this.sysAuthorityService.list(SysAuthorityVo.builder().authorityName("SELLER_USER").build()).getData();
		if(seller_user==null||seller_user.isEmpty()){
			return true;
		}
		return false;
	}

	// 商户清单页面翻页
	@SuppressWarnings("unchecked")
	@PostMapping("sellerlist/page")
	@Decrypt
    @Encrypt
    public Result<PageInfo<SellerAndAccountVo>> page(SellerAndAccountVo avo) {
	
        String json = JSON.toJSONString(avo);
        json = sellerApi.findListSeller(json);
        return Result.of(JSON.parseObject(json, PageInfo.class));
    }
	
	// 商户清单页面不翻页
	@PostMapping("sellerlist/list")
	@Decrypt
    @Encrypt
    public Result<List<SellerAndAccountVo>> list(SellerAndAccountVo avo) {
        String json = JSON.toJSONString(avo);
        json = sellerApi.findListSellerNoPage(json);
        return Result.of(JSON.parseArray(json, SellerAndAccountVo.class));
    }
	
	// 冻结（Y）/删除（D）/解冻（N） 商户
	@SuppressWarnings("unchecked")
	@PostMapping("operation")
	@Decrypt
    @Encrypt
	public Result<Boolean> operation(SellerAndAccountVo avo) {
		return JSON.parseObject(sellerApi.operationSeller(avo.getSellerId(),avo.getSellerState()),Result.class);
	}
	
	// 导入商户
	@SuppressWarnings("unchecked")
	@RequestMapping("importseller")
	@ResponseBody
	public Result<Boolean> importData(@RequestParam("file") MultipartFile file) {
        List<SellerExcelVo> importData = null;
        Result<Boolean> result =  Result.of(true);
        try {
            importData = ExcelUtil.importExcel(file.getInputStream(), SellerExcelVo.class);
        } catch (Exception e) {
        	// 导入异常
            log.error(e.getMessage(),e);
            result = Result.of(false);
            result.setMsg("导入失败！");
            return result;
        }
        try {
	        String json = sellerApi.importSeller(JSON.toJSONString(importData));
	        result = JSON.parseObject(json, Result.class);
        }catch(Exception e) {
        	// 导入异常
            log.error(e.getMessage(),e);
            result.setMsg("导入成功！返回页面有延迟，请勿重复导入。");
        }
		return result;
	}

	@SuppressWarnings("unchecked")
	@PostMapping("qryBalance/page")
	public Result<PageInfo<SellerAndAccountVo>> qryBalancePage(SellerAndAccountVo avo){
		String json = JSON.toJSONString(avo);
		json = sellerApi.qryBalance(json);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}
	


	@SuppressWarnings("unchecked")
	@PostMapping("qryBalance/detail")
	public Result<PageInfo<SellerAccountDetailVo>> qryBalancePageDetail(SellerAccountDetailVo avo){
		String json = JSON.toJSONString(avo);
		json = sellerApi.qryBalanceDetail(json);
		return JSON.parseObject(json, Result.class);
	}
	
	@SuppressWarnings("unchecked")
	@PostMapping("query/detail")
	public Result<PageInfo<SellerProjectVo>> detail(@RequestParam("page") int page,@RequestParam("rows") int rows,@RequestParam("projectCode") String projectCode){
		String json = sellerApi.queryDetail(page,rows,projectCode);
		return Result.of(JSON.parseObject(json, PageInfo.class));
	}


	@RequestMapping("/{fileName}")
	public ResponseEntity upload(@PathVariable String fileName) {
		String fileFullPath = filePath +uploadPath+ fileName;
		try {
			// 由于是读取本机的文件，file是一定要加上的， path是在application配置文件中的路径
			log.info("seller fileFullPath={}",fileFullPath);
			return ResponseEntity.ok(resourceLoader.getResource("file:" + fileFullPath));
		} catch (Exception e) {
			log.error("seller uploadFileName={},path={},error:{}",fileName,fileFullPath,e.getMessage(),e);
			return ResponseEntity.notFound().build();
		}
	}
	@PostMapping("/upload")
	public Result upload(@RequestParam("file") MultipartFile file) {
		if (file.isEmpty()) {
			return Result.of(null,false,"上传失败，请选择文件");
		}
		// 获取文件名
		String fileName = file.getOriginalFilename();
		log.info("seller上传的文件名为：" + fileName);

		// 获取文件的后缀名,比如图片的jpeg,png
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		log.info("seller上传的后缀名为：" + suffixName);

		// 文件上传后的路径
		fileName = UUID.randomUUID() + suffixName;
		log.info("seller转换后的名称:"+fileName);

		File dir=new File(filePath+uploadPath);
		//File dir=new File("D:"+filePath);
		if(!dir.exists()){
			dir.mkdirs();
		}
		File dest = new File(filePath +uploadPath+ fileName);
		//File dest = new File("D:"+filePath + fileName);
		try {
			file.transferTo(dest);
			return Result.of(uploadPath+fileName);
		} catch (IllegalStateException e) {
			log.error("seller upload error:{}",e.getMessage(),e);
		} catch (IOException e) {
			log.error("seller upload error:{}",e.getMessage(),e);
		}
		return Result.of(null,false,"上传失败");
	}
	
	
	@RequestMapping(value = "/downFile")
    public void downFile(HttpServletResponse response,HttpServletRequest request,String fileName) {
        OutputStream out = null;
        FileInputStream fis = null;
        //文件路径
        File dir=new File(filePath+uploadPath+fileName);
		if(!dir.exists()){
			dir.mkdirs();
		}
        try {
            out = response.getOutputStream();
            // 设置response的Header 防止文件名乱码
            response.addHeader("Content-Disposition",
                    "attachment;filename="
                            + new String((fileName).getBytes("utf-8"), "ISO-8859-1"));
            response.setContentType("application/octet-stream");
            fis = new FileInputStream(dir);
            int b;
            while ((b = fis.read()) != -1) {
                out.write(b);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("执行 文件下载downFile 方法失败：" + e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
	
	
	@PostMapping("/query/update")
	public String update(@RequestParam("types") String types,@RequestParam("projectCode") String projectCode){
		String result = sellerApi.update(types,projectCode);
		return result;
	}
	
	
	@SuppressWarnings("unchecked")
	@PostMapping("save")
	@Decrypt
    @Encrypt
    public Result<Boolean> save(SellerAccountDetailVo avo) {
		SysUserVo user = sysUserService.findByLoginName(SecurityUtil.getLoginUser().getUsername()).getData();
        avo.setMerchantNumber(user.getMerchantNumber());
        avo.setPlatform(user.getPlatform());
		return JSON.parseObject(sellerApi.saveSellerInfo(JSON.toJSONString(avo)),Result.class);
    }
	
	/**
	 * 网商商户入驻
	 */
	@PostMapping("insertRegister")
	public void insertRegister(String sellerId){
		sellerApi.insertRegister(sellerId);
	}
	
	
	/**
	 * 查询网商商户入驻结果
	 */
	@PostMapping("registerQuery")
	public void registerQuery(String sellerId){
		sellerApi.registerQuery(sellerId);
	}
	
	
	/**
	 * 修改商户信息
	 */
	@PostMapping("updateRegister")
	public void updateRegister(String sellerId){
		sellerApi.updateRegister(sellerId);
	}
	
	
	/**
	 * 商户信息查询
	 */
	@SuppressWarnings("unchecked")
	@PostMapping("queryRegisterInfo")
	@Decrypt
    @Encrypt
	public Result<Boolean> queryRegisterInfo(SellerAccountDetailVo avo){
		//String json = sellerApi.queryRegisterInfo(sellerId);
		return JSON.parseObject(sellerApi.queryRegisterInfo(avo.getSellerId()),Result.class);
	}
	
	/**
	 * 专户开立
	 */
	@PostMapping("regisOpen")
	public void regisOpen(String sellerId){
		sellerApi.regisOpen(sellerId);
	}
	
	
	/**
	 * 查询网商余额
	 */
	@PostMapping("findWsMoney")
	public String findWsMoney(String sellerId){
		return sellerApi.findWsMoney(sellerId);
	}
	
}
